<template>
  <div class="content-grid">
    <div class="content-header">
      <div class="header-top">
        <h2 class="title">最新推荐</h2>
        <p class="desc">当前最新发布更新的热门资源，我们将会持续保持更新</p>
      </div>
      <!-- 新增分类标签过滤 -->
      <div class="category-tags-wrapper">
        <div class="category-tags">
          <span class="tag"
                v-for="tag in categoryTags"
                :key="tag.id"
                :class="{ active: params.tagId === tag.id }"
                @click="filterByTag(tag.id)">
            {{ tag.name }}
          </span>
        </div>
      </div>
    </div>

    <!-- 加载动画 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <p>加载中...</p>
    </div>

    <!-- 空状态 -->
    <div v-else-if="filteredItems.length === 0" class="empty-container">
      <EmptyState
        :description="'抱歉，没有找到与您选择的标签相关的内容。'"
        :onBackClick="goBack"
        :onRefreshClick="refresh"    :home="false"
      />
    </div>

    <div v-else class="grid-container">
      <content-card v-for="(item, index) in filteredItems"
                    :key="item.id"
                    :item="item"
                    @click="handleItemClick"
                    @imageLoad="handleImageLoad(index)"/>

      <!-- 加载更多按钮 -->
      <div v-if="hasMore" class="load-more" @click="loadMore">
        <div class="load-more-content">
          <svg class="load-more-icon" viewBox="0 0 24 24" width="16" height="16">
            <circle class="circle-bg" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2" fill="none"/>
            <path class="arrow" d="M12 8v8M8 13l4 3 4-3" stroke="currentColor" stroke-width="2" stroke-linecap="round"
                  stroke-linejoin="round"/>
          </svg>
          <span class="load-more-text">加载更多内容</span>
        </div>
      </div>

      <!-- 没有更多数据提示 -->
      <div v-if="!hasMore && !loading && filteredItems.length > 0" class="no-more">
        <div class="no-more-content">
          <div class="line"></div>
          <span>我也是有底线的 ~</span>
          <div class="line"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import ContentCard from './common/ContentCard.vue'
import EmptyState from './EmptyState.vue'
import {getArticlePage, getTagList} from '@/api/portalAPI'

export default {
  name: 'ContentGrid',
  components: {
    ContentCard,
    EmptyState
  },
  data() {
    return {
      loading: true,
      showAll: false,
      activeTag: 'all',
      categoryTags: [
        {id: null, name: '全部'}
      ],
      articleList: [],
      totalArticles: 0,
      hasMore: true,
      params: {
        tagId: null,
        pageNo: 1,
        pageSize: 8
      },
      filteredItems: []
    }
  },
  methods: {
    async getTagLists() {
      this.loading = true; // 开始加载
      try {
        const {code, data, msg} = await getTagList();
        if (code === 0) {
          this.categoryTags = [...this.categoryTags, ...data];
        } else {
          console.error('Error fetching articles:', msg);
        }
      } catch (error) {
        console.error('API call failed:', error);
      } finally {
        this.loading = false; // 加载完成
      }
    },
    async getArticleList() {
      this.loading = true; // 开始加载
      try {
        const {code, data, msg} = await getArticlePage(this.params);
        if (code === 0) {
          // Clear previous articles if loading a new page
          if (this.params.pageNo === 1) {
            this.articleList = [];
          }
          this.articleList.push(...data.list.map(item => ({
            ...item,
            loaded: false
          })));
          this.totalArticles = data.total;

          // 检查是否有更多数据
          this.hasMore = this.articleList.length < this.totalArticles;

          // Initialize filteredItems to show all articles by default
          this.filteredItems = this.articleList; // Ensure filteredItems is initialized
        } else {
          console.error('Error fetching articles:', msg);
        }
      } catch (error) {
        console.error('API call failed:', error);
      } finally {
        this.loading = false; // 加载完成
      }
    },
    handleImageLoad(index) {
      setTimeout(() => {
        this.$set(this.articleList[index], 'loaded', true)
      }, 100)
    },
    handleItemClick(item) {
      // 处理卡片点击事件
      this.$router.push(`/detail/${item.id}`)
    },
    loadMore() {
      if (this.loading || !this.hasMore) return; // Prevent loading if already loading or no more articles
      this.params.pageNo += 1; // Increment page number
      this.getArticleList(); // Fetch more articles
    },
    async filterByTag(tagId) {
      this.loading = true;
      this.params.tagId = tagId;
      this.params.pageNo = 1; // Reset page number for new filter
      this.articleList = []; // Clear current articles
      await this.getArticleList(); // Fetch articles based on the selected tag
      this.filteredItems = this.articleList; // Update filtered items
    },
    goBack() {
      this.$router.push('/'); // 返回首页
    },
   async refresh() {
    await this.getArticleList();
      this.filteredItems = this.articleList; // 刷新数据
    }
  },
  mounted() {
    this.getArticleList()
    this.getTagLists()

  }
}
</script>

<style scoped>
.content-grid {
  background: var(--card-bg);
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  max-width: 100%; /* 确保不超过视口宽度 */
  overflow: hidden; /* 防止溢出 */
}

.content-header {
  margin-bottom: 24px;
}

.header-top {
  margin-bottom: 16px;
  display: flex;
  flex-direction: column;
  align-items: center; /* 只让 header-top 居中 */
}

.title {
  font-size: 24px;
  font-weight: 600;
  color: var(--text-color);
  margin-bottom: 8px;
  text-align: center;
}

.desc {
  color: var(--secondary-color);
  font-size: 14px;
  text-align: center;
  max-width: 600px;
  margin: 0 auto;
}

/* 修改分类标签样式 */
.category-tags-wrapper {
  width: 100%;
  overflow-x: auto;
  -webkit-overflow-scrolling: touch; /* 提升移动端滚动体验 */
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
}

.category-tags-wrapper::-webkit-scrollbar {
  display: none; /* Chrome, Safari and Opera */
}

.category-tags {
  display: flex;
  gap: 12px;
  margin-top: 16px;
  padding: 4px 0; /* 添加内边距防止阴影被裁剪 */
}

.tag {
  padding: 6px 16px;
  border-radius: 20px;
  background: var(--hover-color);
  color: var(--secondary-color);
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
  white-space: nowrap; /* 防止标签换行 */
}

.tag:hover, .tag.active {
  background: var(--primary-color);
  color: white;
}

.grid-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); /* 自适应列数 */
  gap: 20px;
  width: 100%; /* 确保宽度为100% */
}

.grid-item {
  background: var(--card-bg);
  border-radius: 4px;
  overflow: hidden;
  transition: all 0.3s;
  cursor: pointer;
  position: relative;
  border: 1px solid var(--border-color);
}

.grid-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.item-tags {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 2;
  display: flex;
  gap: 8px;
}

.tag-type,
.tag-category {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  color: white;
  background: rgba(0, 0, 0, 0.6);
  backdrop-filter: blur(4px);
}

.item-image {
  position: relative;
  padding-top: 56.25%; /* 16:9 比例 */
  overflow: hidden;
  background: var(--hover-color);
  border-radius: 4px 4px 0 0;
}

.item-image img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  object-position: center;
  transition: transform 0.3s ease-out;
  opacity: 0;
  will-change: transform;
}

.item-image img.loaded {
  opacity: 1;
  transition: opacity 0.3s ease-in;
}

.grid-item:hover .item-image img.loaded {
  transform: scale(1.05);
}

.item-info {
  padding: 12px;
  background: var(--card-bg);
}

.item-title {
  font-weight: normal;
  line-height: 1.4;
  margin-bottom: 10px;
  color: var(--text-color);
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  height: 40px;
}

.item-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: var(--secondary-color);
  font-size: 13px;
}

.meta-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.dot {
  color: var(--border-color);
}

.meta-right {
  display: flex;
  gap: 12px;
}

.likes,
.comments {
  display: flex;
  align-items: center;
  gap: 4px;
  transition: color 0.3s;
}

.likes:hover,
.comments:hover {
  color: var(--primary-color);
}

.likes.active {
  color: #ff4757;
}

.likes.active i {
  animation: heart-beat 0.3s;
}

@keyframes heart-beat {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.2);
  }
  100% {
    transform: scale(1);
  }
}

/* 加载动画样式 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: var(--secondary-color);
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid var(--border-color);
  border-top-color: var(--primary-color);
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 10px;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

/* 加载更多按钮样式 */
.load-more {
  grid-column: 1 / -1;
  padding: 40px 0;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
}

.load-more-content {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 12px 28px;
  background: var(--card-bg);
  border: 1px solid var(--border-color);
  border-radius: 25px;
  color: var(--secondary-color);
  font-size: 14px;
  transition: all 0.3s;
  position: relative;
  left: 50%;
  transform: translateX(-50%);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.load-more:hover .load-more-content {
  color: var(--primary-color);
  border-color: var(--primary-color);
  background: linear-gradient(to right, var(--hover-color), var(--card-bg));
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.load-more-text {
  margin-left: 8px;
  font-weight: 500;
}

.load-more-icon {
  transition: all 0.3s;
  width: 20px;
  height: 20px;
}

.circle-bg {
  opacity: 0.2;
}

.arrow {
  transform-origin: center;
  transition: transform 0.3s;
}

.load-more:hover .load-more-icon {
  animation: bounce 1s infinite;
}

@keyframes bounce {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(3px);
  }
}

/* 没有更多数据提示样式 */
.no-more {
  grid-column: 1 / -1;
  text-align: center;
  padding: 40px 0;
  color: var(--secondary-color);
  font-size: 14px;
}

.no-more-content {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 20px;
}

.line {
  width: 60px;
  height: 1px;
  background: linear-gradient(to right, transparent, var(--border-color), transparent);
}

@media (max-width: 1400px) {
  .grid-container {
    grid-template-columns: repeat(4, 1fr);
  }
}

@media (max-width: 1200px) {
  .grid-container {
    grid-template-columns: repeat(3, 1fr);
    gap: 12px;
  }
}

@media (max-width: 992px) {
  .grid-container {
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;
  }

  .content-header .title {
    font-size: 20px;
  }
}

@media (max-width: 768px) {
  .content-grid {
    padding: 15px 10px;
  }

  .grid-container {
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;
  }

  .grid-item {
    border-radius: 4px;
  }

  .item-image {
    border-radius: 4px 4px 0 0;
  }

  .item-info {
    padding: 10px;
  }

  .item-title {
    font-size: 13px;
    margin-bottom: 8px;
    height: 36px;
  }

  .item-meta {
    font-size: 12px;
  }

  .content-header {
    margin-bottom: 20px;
  }

  .header-top {
    margin-bottom: 12px;
  }

  .title {
    font-size: 20px;
    margin-bottom: 6px;
  }

  .desc {
    font-size: 13px;
    max-width: 100%; /* 移动端不限制宽度 */
  }

  .load-more {
    padding: 30px 0;
  }

  .load-more-content {
    padding: 10px 24px;
    font-size: 13px;
  }

  .load-more-icon {
    width: 18px;
    height: 18px;
  }

  .no-more {
    padding: 30px 0;
    font-size: 13px;
  }

  .line {
    width: 40px;
  }

  .category-tags {
    padding: 4px 0;
    margin-top: 12px;
    gap: 8px;
  }

  .tag {
    padding: 4px 12px;
    font-size: 13px;
  }

  .empty-container {
    min-height: 400px;
    margin: 15px 0;
  }
}

@media (max-width: 480px) {
  .title {
    font-size: 18px;
  }

  .desc {
    font-size: 12px;
  }

  .tag {
    padding: 3px 10px;
    font-size: 12px;
  }

  .empty-container {
    min-height: 350px;
    margin: 10px 0;
  }
}

/* 添加图片加载动画 */
.image-placeholder {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(
      90deg,
      var(--border-color) 25%,
      var(--hover-color) 50%,
      var(--border-color) 75%
  );
  background-size: 200% 100%;
  animation: loading 1.5s infinite linear;
  will-change: background-position;
  z-index: 1;
}

@keyframes loading {
  0% {
    background-position: 200% 0;
  }
  100% {
    background-position: -200% 0;
  }
}

/* 新增空状态容器样式 */
.empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 500px;
  width: 100%;
  background: var(--card-bg);
  border-radius: 12px;
  margin: 20px 0;
}
</style>
